define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');

    require('../../su/accordion/oaSearchCurtainCtrl');
    /**
     * Created with IntelliJ IDEA.
     * User: teddy zhang
     * Date: 2015-03-23
     * Time: 16:06
     */

    $.widget('rk.wrSearchCurtainCtrl', $.rk.oaSearchCurtainCtrl, {
        _curtain: null,
        options: {
            templateId: '',
            data: {},
            parentHolder: null,
            act: 'mine'
        },
        _create: function() {
            var _ = this,
                elem = _.element,
                opt = _.options;
            _._check();
            _._setCurtain(opt.parentHolder);
            _._render();

        },

        _check: function() {
            var me = this;
            var elem = this.element;
            if (!me.options.templateId || !me.options.parentHolder) throw new TypeError()
        },

        _render: function() {
            var me = this,
                elem = me.element,
                opt = me.options,
                _id = opt.templateId,
                _data = opt.data;

            me._curtain = opt.parentHolder


            //加载模板

            //加载模板
            require.async(_id, function(tpl) {
                var tpl_html = rk.templateText(tpl, $.extend({}, _data))
                me._curtain.html(tpl_html);

                //初始化模板（初始化button,初始化 部门选择，初始化提交人选择）
                me._initSearch();
                //绑定事件 (自定义选择事件,搜索事件，取消事件，关闭事件)
                me._bind();

                me._curtain.find('.oa-curtain-body:first').beScroll();

            });
        },

        _initSearch: function() {
            var me = this;
            var elem = me.element;

            var curtain_content = me._getCurtain();
            var $departmentElem = $('#reportDepartmentID');
            var $userElem = $('#reportUserID');


            // $.each($(curtain_content).find('div.ui-radio-buttonset,div.ui-check-buttonset'), function(idx, value) {
            //     $(value).buttonset();
            // });
            $(curtain_content).find('div.ui-radio-buttonset,div.ui-check-buttonset').each(function() {
                $(this).parent().buttonset();
            });

            $departmentElem.multitreeselector({
                source: '/json/crm_dimension/dim-oa-departs.action'
            });
            $userElem.multipeopleselector({});

        },

        _setCurtain: function(curtainPanel) {
            var me = this;
            me._curtain = curtainPanel;
        },
        _getCurtain: function() {
            var me = this;
            return me._curtain;
        },

        _bind: function() {
            var me = this;
            var elem = me.element;

            var _curtain = me._getCurtain();
            _curtain.find('input.start-date').datepicker({
                dateFormat: 'yy-mm-dd'
            }).val(moment().startOf('month').format('YYYY-MM-DD'));
            _curtain.find('input.end-date').datepicker({
                dateFormat: 'yy-mm-dd'
            }).val(moment().format('YYYY-MM-DD'));

            _curtain.find("#custom_date").bind("click", function(event) {
                _curtain.find("tr[attr = 'report_date_custom']").show();
                me._repositionList();
            });

            _curtain.find("input[name ='report_date']").not("#custom_date").bind("click", function(event) {
                _curtain.find("tr[attr = 'report_date_custom']").hide();
                me._repositionList();
            });

            _curtain.find('a[act="close_oa_curtain"]').bind('click', function() {
                me.closeMe();
            });


            _curtain.find('a[act="adv-search-back"]').bind('click', function() {
                me.closeMe();
            });


            //搜索事件

            _curtain.find("a[act = 'adv-search-btn']").click(function() {
                me._search();
            });


        },

        _getQueryData: function() {
            var me = this;
            var elem = me.element;
            var curtain = me._getCurtain();
            var data = {
                viewType: "" //default, mark as search request for back-end
            };
            //reportTypes
            var report_types = [];
            curtain.find("input[name= 'report_type']").each(function() {
                var checkbox = $(this);
                if (checkbox.is(':checked')) report_types.push(checkbox.attr('val'));
            })
            report_types = report_types.join(",");
            if (report_types) data.reportTypes = report_types;

            //date
            var radio = elem.find("input[name= 'report_date']:checked");
            var ms_range;
            if (radio.size() > 0) {
                ms_range = me._getMilliseconds(radio.attr('val'));
                if (ms_range) {
                    data.startTime = moment(ms_range.start).add(1, 'millisecond').unix() * 1000;
                    data.endTime = moment(ms_range.end).subtract(1, 'millisecond').unix() * 1000;
                }

            }

            //status
            var report_status = [];
            var status_checkboxes = curtain.find("input[name ='report_status']");
            status_checkboxes.each(function() {
                var checkbox = $(this);
                if (checkbox.is(':checked')) report_status.push(checkbox.attr('val'));
            });
            report_status = report_status.join(',');
            if (report_status) data.reportStatus = report_status;

            //userIds
            var userIds = [];
            var usersInput = $('#reportUserID').multipeopleselector("val");
            if (curtain.find('tr[attr="report_user"]').is(':visible') && usersInput) {
                $.each(usersInput, function(idx, user) {
                    userIds.push(user.value);
                });
                data.userIds = userIds.join(",");
            }
            //departments
            var departmentsInput = $('#reportDepartmentID');
            if (curtain.find('tr[attr="report_department"]').is(':visible')) {
                var arr = departmentsInput.multitreeselector("val");
                if (arr && arr.length > 0) {
                    var vals = [];
                    for (var i = 0, len = arr.length; i < len; i++) {
                        var o = arr[i];
                        vals.push(o.value);
                    }
                    data.departIds = vals.join(',')
                }
            }
            return data;
        },


        _getMilliseconds: function(dateType) {
            var me = this;
            var elem = me.element;
            var range = {};
            switch (dateType) {
                case 'thisweek':
                    var mon = moment().startOf('isoWeek');
                    var sun = moment(mon);
                    sun.add(7, 'day');
                    //__alert( mon.format()+','+sun.format() );
                    range.start = mon.unix() * 1000;
                    range.end = sun.unix() * 1000;
                    break;
                case 'lastweek':
                    var mon = moment().startOf('isoWeek');
                    mon.subtract(7, 'days');
                    var sun = moment(mon);
                    sun.add(7, 'day');
                    //__alert( mon.format()+','+sun.format() );
                    range.start = mon.unix() * 1000;
                    range.end = sun.unix() * 1000;
                    break;
                case 'thismonth':
                    var firstday = moment().startOf('month');
                    var lastday = moment(firstday);
                    lastday.add(1, 'month');
                    //__alert( firstday.format()+','+lastday.format() );
                    range.start = firstday.unix() * 1000;
                    range.end = lastday.unix() * 1000;
                    break;
                case 'lastmonth':
                    var firstday = moment().startOf('month');
                    firstday.subtract(1, 'month');
                    var lastday = moment(firstday);
                    lastday.add(1, 'month');
                    //__alert( firstday.format()+','+lastday.format() );
                    range.start = firstday.unix() * 1000;
                    range.end = lastday.unix() * 1000;
                    break;
                case 'others':
                    var startInput = elem.find('input.start-date');
                    var endInput = elem.find('input.end-date');
                    var start = moment(startInput.val());
                    var end = moment(endInput.val());
                    //__alert( start.format()+','+end.format() );
                    if (end.isBefore(start)) {
                        rk.noticeError(rk.i18n('WORKREPORT_FORM_SUBMIT_MESSAGE_1'));
                    } else {
                        range.start = start.unix() * 1000;
                        range.end = end.unix() * 1000;
                    }
                    break;
                default:
            }

            if (range.start && range.end)
                return range;
        },


        _search: function() {
            var me = this;
            var elem = me.element;
            var data = me._getQueryData();
            var opt = me.options;
            var curtain = me._getCurtain();

            if (!data) return;
            var newData = {};
            newData['search.viewType'] = '';
            for (var key in data) {
                var val = data[key];
                if (val && typeof val != 'function') {
                    newData['search.' + key] = val;
                }
            }
            me._loadData(newData, 1);


        },
        _loadData: function(newData, pageNo) {
            var me = this;
            var elem = me.element;
            var data = me._getQueryData();
            var opt = me.options;
            var curtain = me._getCurtain();

            var search_blank_HTML = '<div class="oa-search-blank" ><p>' + rk.i18n('WORKREPORT_NO_SEARCH_RESULTS') + '</p></div>';


            //请求
            newData['pageNo'] = pageNo;
            $.getJSON(rk.oa.getRequestUrl('workreport.' + opt.act), newData, function(data) {
                if (!data.status) {
                    var data = data.data;
                    var results = data.results;
                    var users = data.users;
                    var num = data.data_count;
                    var templateId = 'oa/tmpl/workreport/asset/template_my_row.tpl';
                    if (opt.act == 'received' || opt.act == 'subordinate') {
                        templateId = 'oa/tmpl/workreport/asset/template_collage_row.tpl';
                    }

                    if (num === 0) {
                        curtain.find("div.oa-tab-header span.number").text(0);
                        curtain.find("div.oa-tab-body").html(search_blank_HTML);
                    } else {
                        curtain.find("div.oa-tab-body").html("");
                        curtain.find("div.oa-tab-header span.number").text(num);

                        var listbody = curtain.find("div.oa-tab-body");

                        if (listbody.find('[act="list"]').size() == 0) {
                            listbody.html('<div act="list"></div>');
                            var list = listbody.find('div[act="list"]');
                            list.wrListCtrl({
                                viewtype: opt.act
                            });
                        }
                        var list = listbody.find('div[act="list"]');
                        list.wrListCtrl('bindData', results, templateId);

                        var pagingdiv = curtain.find("div.oa-result-footer > div");
                        pagingdiv.rkPaging({
                            pagenum: pageNo, //（可选）当前页数，默认1
                            pagesize: 20, //（可选）当前每页显示条数，默认20
                            rowscount: num, //所有数据数
                            onChange: function(pagenum) {
                                me._loadData(newData, pagenum);

                            }
                        });

                    }
                    curtain.find("div.oa-accordion-content").show();

                    me._repositionList();
                }
            });
        }


    });

});
